#!/bin/bash
#This script is dynamic mount container volumens
set -e
PID=$1
HOSTPATH=$2
CONTPATH=$3
NSENTER_PATH=$4

if [ ! -d $HOSTPATH ];then
    echo "physics $HOSTPATH is not exist!"
    exit 1
fi

REALPATH=$(readlink --canonicalize $HOSTPATH)

FILESYS=$(df -P $REALPATH | tail -n 1 | awk '{print $6}')

while read DEV MOUNT JUNK
    do
        [ $MOUNT = $FILESYS ] && [ $DEV != "rootfs" ] && break
    done </proc/mounts
[ $MOUNT = $FILESYS ] # Sanity check!

while read A B C SUBROOT MOUNT JUNK
    do [ $MOUNT = $FILESYS ] && break
    done < /proc/self/mountinfo

[ $MOUNT = $FILESYS ] # More sanity check!
SUBPATH=$(echo $REALPATH | sed s,^$FILESYS,,)
REALDEV=$(readlink --canonicalize $DEV)
DEVDEC=$(printf "%d %d" $(stat --format "0x%t 0x%T" $REALDEV))
run_command="$NSENTER_PATH --target $PID --mount --uts --ipc --net --pid -- /bin/sh -c"
if  [ `$run_command "export PATH=/usr/bin:/bin:/sbin;mount|grep $CONTPATH|wc -l"` -ne 0 ];then
    echo "container  mount dir $CONTPATH is mounting!"
    exit 0
fi
$run_command "export PATH=/usr/bin:/bin:/sbin;mkdir -p $(dirname $DEV)"
$run_command "export PATH=/usr/bin:/bin:/sbin;[ -b $DEV ] ||mknod --mode 0600 $DEV b $DEVDEC"
$run_command "export PATH=/usr/bin:/bin:/sbin;mkdir /tmpmnt"
$run_command "export PATH=/usr/bin:/bin:/sbin;mount $DEV /tmpmnt"
$run_command "export PATH=/usr/bin:/bin:/sbin;mkdir -p $CONTPATH"
$run_command "export PATH=/usr/bin:/bin:/sbin;mount -o bind /tmpmnt/$SUBROOT/$SUBPATH $CONTPATH"
$run_command "export PATH=/usr/bin:/bin:/sbin;umount /tmpmnt"
$run_command "export PATH=/usr/bin:/bin:/sbin;rmdir /tmpmnt"
check_result=`$run_command "export PATH=/usr/bin:/bin:/sbin;mount|grep $CONTPATH|wc -l"`
echo check_result
if [ $check_result -ne 0 ];then
    echo "dynamic mount physics $HOSTPATH on $PID $CONTPATH is success!"
    exit 0
else
    echo "dynamic mount physics $HOSTPATH on $PID $CONTPATH is fail!"
    exit 1
fi
